<template>
  <PageContainer>
    <Header :title="formData.id ? '编辑产品与服务' : '添加产品与服务'" />
    <view class="hb-p-4">
      <tm-form
        @submit="handleSubmit"
        layout="vertical"
        :model-value="formData"
        :margin="[0, 0]"
        :padding="[0, 0]"
        :border="false"
        :label-align="'top'"
        :transparent="true"
      >
        <!-- 产品/服务图片上传区域 -->
        <view class="hb-bg-white hb-rounded-lg hb-p-3 hb-box-shadow-base hb-mb-2.5">
          <tm-form-item
            required
            field="imagesList"
            label="产品/服务图片"
            :border="false"
            :margin="[0, 0]"
            :rules="[{ required: true, message: '请上传产品/服务图片' }]"
            :errorLabel="''"
          >
            <ShmilyDragImage
              v-model:model-value="formData.imagesList"
              :cols="4"
              :addImage="handleAddImage"
              :border-radius="16"
              @del="delResultItem"
            />
          </tm-form-item>
        </view>
        <!-- 产品/服务名称输入区域 -->
        <view class="hb-bg-white hb-rounded-lg hb-p-3 hb-box-shadow-base hb-mb-2.5">
          <tm-form-item
            required
            field="name"
            label="产品/服务名称"
            :border="false"
            :margin="[0, 0]"
            :rules="[{ required: true, message: '请输入产品/服务名称' }]"
            :errorLabel="''"
          >
            <TmInput
              v-model="formData.name"
              :height="88"
              :font-size="28"
              :maxlength="40"
              :inputPadding="[16, 0]"
              placeholder="产品/服务名称"
            />
          </tm-form-item>
        </view>

        <!-- 产品/服务介绍输入区域 -->
        <view class="hb-bg-white hb-rounded-lg hb-p-3 hb-box-shadow-base hb-mb-2.5">
          <tm-form-item
            field="description"
            label="产品/服务介绍"
            :border="false"
            :margin="[0, 0]"
            :errorLabel="''"
          >
            <TmInput
              v-model="formData.description"
              :height="160"
              :font-size="28"
              type="textarea"
              :inputPadding="[16, 16]"
              placeholder="请输入产品/服务的具体介绍描述"
            />
          </tm-form-item>
        </view>

        <!-- 小程序链接输入区域 -->
        <view class="hb-bg-white hb-rounded-lg hb-p-3 hb-box-shadow-base hb-mb-2.5">
          <tm-form-item
            field="link"
            label="小程序链接"
            :border="false"
            :margin="[0, 0]"
            :errorLabel="''"
          >
            <view class="hb-text-sm hb-text-[#969799] hb-mb-3">
              配置小程序链接后，可进行页面跳转；您可以将您的产品链接配置到这。
            </view>
            <TmInput
              v-model="formData.link"
              :height="88"
              :font-size="28"
              :inputPadding="[16, 0]"
              placeholder="请输入小程序链接"
            />
          </tm-form-item>
        </view>

        <!-- 底部确认按钮 -->
        <BottomSubmit
          :submit-loading="loading"
          submitBtnLabel="保存"
          :submitBtnColor="'#2878FF'"
          cancelBtnLabel="删除"
          :hideCancelBtn="!formData.id"
          @cancel="handleDelete"
        />
      </tm-form>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  import { FunctionArgs } from '@vueuse/core';
  import { ProductInfo } from '@/api/card/type';
  import ImgUpload from '@/components/ImgUpload/index.vue';
  import ShmilyDragImage from '@/components/ImgUpload/shmily-drag-image.vue';
  import {
    addOrUpdateProductService,
    deleteProductService,
    getProductServiceById,
  } from '@/api/card';
  import { useUpload } from '@/hooks/file/useUpload';
  import { useUserStore } from '@/store/modules/user';
  import { debounce } from 'lodash-es';
  const userStore = useUserStore();

  /* productServiceEdit 编辑产品与服务 */
  let id: number | undefined;
  let success: FunctionArgs | undefined;
  customOnload<'productServiceEdit'>((options) => {
    id = options.id;
    success = options.success;
    queryProductServiceById();
  });

  // 表单数据
  const formData = reactive<ProductInfo>({
    name: '',
    description: '',
    imagesList: [],
    linkType: '',
    link: '',
  });

  // 加载状态
  const loading = ref(false);
  const { successResult, chooseFile, result, addResultItem, delResultItem } = useUpload({
    count: 6,
    isCrop: false,
  });

  // 获取产品与服务详情
  const queryProductServiceById = async () => {
    if (!id) return;
    const res = await getProductServiceById(id!);
    formData.name = res.name;
    formData.description = res.description;
    formData.imagesList = res.imagesList;
    formData.linkType = res.linkType;
    formData.link = res.link;
    formData.id = res.id;
    formData.imagesList = res.imagesList || [];
    res.imagesList.forEach((item) => {
      addResultItem({
        filePath: item,
        progress: 100,
      });
    });
  };

  watch(
    () => successResult.value,
    (v) => {
      formData.imagesList = [...v.map((item) => item.filePath!)];
    },
    {
      deep: true,
    },
  );
  // 添加图片
  const handleAddImage = () => {
    chooseFile({ mediaType: 'image' });
  };

  // 删除产品与服务
  const handleDelete = async () => {
    await deleteProductService(formData.id!);
    uni.showToast({
      title: '删除成功',
      icon: 'success',
    });
    setTimeout(() => {
      success?.();
      navigateBack();
    }, 1000);
  };

  // 提交申请
  const handleSubmit = debounce(async (e: Tmui.tmFormSubmitResult<typeof formData>) => {
    // 表单验证
    if (!e.isPass) return;
    // 防止重复提交
    if (loading.value) return;
    loading.value = true;
    // 使用表单验证
    try {
      await addOrUpdateProductService(formData);
      userStore.getUserInfo();
      uni.showToast({
        title: '保存成功',
        icon: 'success',
      });
      setTimeout(() => {
        success?.();
        navigateBack();
      }, 1000);
    } catch (e) {
      console.error('表单验证失败', e);
    } finally {
      loading.value = false;
    }
  }, 200);
</script>

<style lang="scss" scoped></style>
